<?php
namespace App\Http\Controllers;
use App\Cafe_user;
use App\Cafe;
use App\Partner;
use App\Photo;
use App\Goods;
use App\Message;
use App\DeliveryAddress;
use App\Beans;
use App\Tasks;
use App\Cafes_tags;
use App\Cafes_supplys;
use App\Supply_tags;
use App\Captcha;
use App\Supplys;
use App\Party;
use App\Sales;
use App\Sale_order;
use App\Party_user;
use App\Party_supply;
use App\Cupping_data;

use App\Dicts;
use App\Tags;
use App\UserPartner;
use App\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis as Redis;
use Illuminate\Support\Facades\DB;
use function MongoDB\BSON\toJSON;

class API3Controller extends Controller
{

    public function partyUpdate(Request $request){
        $id = $request->id;
        $photos = $request ->photos;
        $photosArr=json_decode($photos);
        $party = Party::find($id);
        $photos = $party->photos;
        foreach ($photos as $photo){
            $photo->delete();
        }
        foreach ($photosArr as $item){
            $photo = new Photo();
            $photo -> url = $item->url;
            if(str_contains($item->url, "http://onecafe")){
                $url=$item->url."?imageInfo";
                $url = substr($url, 0, 26) . "pictj" . substr($url, 31);
                $rs=dealHttp($url);
                $width=$rs->width;
                $height=$rs->height;
                $photo->width=$width;
                $photo->height=$height;
            }

            $photo -> party_id =$id;
            $photo -> body = $item -> body ?: "";
            $photo -> save();
        }
        return response()->json(0);

    }
    //返回短信验证码，随机数字字符串，存入captcha，返回
    public function Impl_getCaptcha(Request $request)
    {   
        $captcha = new Captcha();
        $captcha->phone=$request->input('phone'); 
        $captcha->captcha=rand(1000,9999);
        $captcha->captcha_time=time();
        $sms = json_decode($this->send_sms($captcha->phone,$captcha->captcha));
        $captcha->save();
        $captcha->code = $sms->code;
        return response()->json($captcha);

    }
    //手机号注册，验证码核对，更新手机号
    public function Impl_phoneRegister(Request $request)
    {   

        $count = Captcha::where('phone',$request->input('phone'))
                ->where('captcha',$request->input('captcha'))
                ->count();
        
        if($count)
        {
            Captcha::where('phone',$request->input('phone'))
                ->where('captcha',$request->input('captcha'))
                ->delete();

            //更新用户手机号！！！！！
            $user = $this->getUserByAppUserSession($request->input('userSession'));

            $user = Users::find($user->id);
            $user->phone = $request->input('phone');
            $user->save();
            return 1;
        }
        else
            return 0;
    }
    private function send_manageSms($mobile, $content){
        $apikey = "db34f598bb6cd79147020744b5b9dff0"; //请用自己的apikey代替
        $text="【一间咖啡馆】有".$content."的咖啡馆加入平台，请到公众号中审核";
        $url="http://yunpian.com/v1/sms/batch_send.json";
        $encoded_text = urlencode("$text");
        $mobile.=",15898965731";
        $mobile = urlencode("$mobile");
        $post_string="apikey=$apikey&text=$encoded_text&mobile=$mobile";
        return $this->sock_post($url, $post_string);
    }
    private function sock_post($url,$query){
        $data = "";
        $info=parse_url($url);
        $fp=fsockopen($info["host"],80,$errno,$errstr,30);
        if(!$fp){
            return $data;
        }
        $head="POST ".$info['path']." HTTP/1.0\r\n";
        $head.="Host: ".$info['host']."\r\n";
        $head.="Referer: http://".$info['host'].$info['path']."\r\n";
        $head.="Content-type: application/x-www-form-urlencoded\r\n";
        $head.="Content-Length: ".strlen(trim($query))."\r\n";
        $head.="\r\n";
        $head.=trim($query);
        $write=fputs($fp,$head);
        $header = "";
        while ($str = trim(fgets($fp,4096))) {
            $header.=$str;
        }
        while (!feof($fp)) {
            $data .= fgets($fp,4096);
        }
        return $data;
    }
    public function Impl_beansList(Request $request)
    {
        $cafe_id=$request->input('cafe_id');
        $allPublicBeans=Beans::where('public',1)->get();      
        $allPrivateBeans=Beans::where('cafe_id',$cafe_id)->get();  
        
        $beans = $allPrivateBeans->merge($allPublicBeans);
        return response()->json($beans);
    }
    public function Impl_dictDetail(Request $request){
        $dict_id=$request->input('dict_id');
        $dict=Dicts::find($dict_id);
        // var_dump($dict);
        return response()->json($dict);
    }

    public function Impl_cafeFlavours(Request $request)
    {
        // $cafe_id=$request->input('cafe');
        return response()->json($this->getCafeFlavours($request->input('cafe')));
    }

    public function Impl_partyInfo(Request $request){
        $id=$request->input('party_id');
        $party=Party::find($id);

        $party->cafe=$party->cafe;
        $party->sales=$party->sales;
        $party->cupping=$this->getPickerDataFromDictsByID('cupping',$party->cupping);
        
        return response()->json($party);
    }
    public function Impl_supplyDetail(Request $request){
        $supply_id=$request->input('supply_id');
        $supply=Supplys::find($supply_id);

        if(!empty($supply->method))
            $supply->method=$this->getPickerDataFromTagsByID(15,$supply->method);
        if(!empty($supply->roast))
            $supply->roast=$this->getPickerDataFromTagsByID(18,$supply->roast);
        

        $supply->species=$this->getPickerDataFromArr(Dicts::find(13)->showtags()->get(),$supply->species);
        
        if($supply->continent==0)       //如果没有，默认第一个（非洲）
            $supply->continent=11;
        
        $supply->country=$this->getPickerDataFromTagsByID($supply->continent,$supply->country);
        $supply->continent=$this->getPickerDataFromDictsByID('continent',$supply->continent);

        
        $supply->flavourTags=$this->getCafeFlavours($supply->cafe);


        $photos = $supply->photos()->get();
        $photos=$photos->sortBy('sort');
        $thePhotos = collect();  
        $sort = 1;
        foreach ($photos as $photo) {
            $photo->sort = $sort;
            $photo->save();
            $sort++;
            $thePhotos->push($photo);
        }
        $photos = $thePhotos->sortBy("sort");
        $supply->photos=$photos;

        $supply->flavours=$supply->tags;    

        return response()->json($supply);
    }
    public function Impl_supplyImgs(Request $request){
        $supply_id=$request->input('supply_id');
        $supply=Supplys::find($supply_id);

        if($supply->continent)
        {
            $supply->continent=$supply->getContinent;
        }
        if($supply->country)
        {
            $supply->country=$supply->getCountry;
        }
        
        $photos = $supply->photos()->get();
        $photos=$photos->sortBy('sort');
        $thePhotos = collect();  
        $sort = 1;
        foreach ($photos as $photo) {
            $photo->sort = $sort;
            $photo->save();
            $sort++;
            $thePhotos->push($photo);
        }
        $photos = $thePhotos->sortBy("sort");
        $supply->photos=$photos;

        return response()->json($supply);
    }

    private function getCafeFlavours($cafe)
    {
        $flavourTags=Tags::where('category',19)->orderBy('sort', 'asc')->get();

        $publicFlavours=$flavourTags->where('public',1);      
        $cafeFlavours=$flavourTags->where('cafe',$cafe);      
        return $cafeFlavours->merge($publicFlavours);

    }

    private  function  getPickerDataFromTagsByID($dict,$tag_id){
        $tagsArr=array();
        $tags=Dicts::find($dict)->showtags()->orderBy('sort', 'asc')->get();
        if($tag_id)
            $index=Tags::where('id',$tag_id)->first()->sort-1;
        if(empty($index))
            $index=0;
        $tagsArr['tags']=$tags;
        $tagsArr['index']=$index;
        return $tagsArr;
    }
    private  function  getPickerDataFromDictsByID($category,$dict_id){
        $dictsArr=array();
        $dicts=Dicts::where('category',$category)->orderBy('sort', 'asc')->get();
        
        $index = 0;
        foreach ($dicts as $dict) {
            if($dict->id == $dict_id)
                break;
            $index++;  
        }
        if(!$dict_id)
            $index=0;

        $dictsArr['dicts']=$dicts;
        $dictsArr['index']=$index;
        return $dictsArr;
    }

    public function Impl_beanDetail(Request $request){
        $bean_id=$request->input('bean_id');
        $bean=Beans::find($bean_id);
        
        $bean->continent = $bean->continent;
        $bean->country = $bean->country;


        $flavourTags=Tags::where('category',19)->orderBy('sort', 'asc')->get();

        $publicFlavours=$flavourTags->where('public',1);      
        $cafeFlavours=$flavourTags->where('cafe',$request->input('cafe_id')); 
        $bean->flavourTags=$cafeFlavours->merge($publicFlavours);

        return response()->json($bean);
    }


    /*
     * appSupply接口
     */
    public function Impl_tagCreate(Request $request){
        $cafe=$request->input('cafe');
        $category=$request->input('category');
        $public=$request->input('public');
        $flavour=$request->input('flavour');
        
        $tag=new Tags;
        $tag->name=$flavour;
        $tag->cafe=$cafe;
        $tag->category=$category;
        $tag->public=$public;
        $tag->save();

        return response()->json($tag);
    }
    public function Impl_tagUpdate(Request $request){
        $tag_id=$request->input('tag_id');
        $category=$request->input('category');
        $partner_id=$request->input('partner_id');
        $name=$request->input('name');
    
        if($tag_id>0)
        {
            $tag=Tags::find($tag_id);
            $tag->name=$name;
            $tag->category=$category;
            $tag->partner_id=$partner_id;
            $tag->save();
        }
        else
        {
            $tag=new tags; 
            $tag->name=$name;
            $tag->category=$category;
            $tag->partner_id=$partner_id;
            $tag->save();
        }

        return response()->json($tag);
    }

    public function Impl_goodsUpdate(Request $request){
        $goods_id=$request->input('goods_id');
        $name=$request->input('name');
        $tag_id=$request->input('tag_id');
        $icon=$request->input('icon');
        $partner_id=$request->input('partner_id');
        $user = $this->getUserByAppUserSession($request->input('loginSession'));

        if($goods_id>0)
        {
            $goods=Goods::find($goods_id);
        }
        else
        {
            $goods=new Goods;
            $goods->name=$name;
            $goods->user_id=$user->id;
            $goods->tag_id=$tag_id;
            $goods->partner_id=$partner_id;
        }

        //生成产品二维码
        if($goods->partner_id)
        {
            $partner=Partner::find($goods->partner_id);
            if($partner->logo)
            {
                $logo=$partner->logo;
                $path="pages/front/goods/detail/detail?goods_id=$goods->id";
                $qrcode=createQrcode($path,$logo);
                $goods->qrcode=$qrcode;
            }
        }
        
        


        $goods->title=$name;
        $goods->icon=$icon;
        $goods->save();

        return response()->json($goods);
    }

    /*
     * party
     */
    public function partyNew2(Request $request){
//        $party = new Partys();
//        $party->save();
//        $photos =
//        return $party->id;

    }
    public function Impl_partyCreate(Request $request){
        $party_id=$request->input('party_id');
        $name=$request->input('name');
        $banner=$request->input('banner');
        $bean_count=$request->input('bean_count');
        $user_count=$request->input('users_count');
        $cafe_id=$request->input('cafe_id');
        $from_date=$request->input('from_date');
        $from_time=$request->input('from_time');
        $phone=$request->input('phone');
        $price=$request->input('price');
        $password=$request->input('password');
        $summary=$request->input('summary');
        $cupping=$this->getDictValue('cupping',$request->input('cupping')+1); //得到处理方式tagid


        if($party_id)    //更新
        {
            $party=Party::find($party_id);
            $party->name=$name;
            $party->banner=$banner;
            $party->bean_count=$bean_count;
            $party->user_count=$user_count;
            $party->cafe_id=$cafe_id;
            $party->from_date=$from_date;
            $party->from_time=$from_time;
            $party->password=$password;
            $party->phone=$phone;
            $party->summary=$summary;
            $party->cupping=$cupping;

            $party->save();

        }
        else            //新增
        {
            $party=new Party;
            $party->name=$name;
            $party->banner=$banner;
            $party->bean_count=$bean_count;
            $party->user_count=$user_count;
            $party->cafe_id=$cafe_id;
            $party->from_date=$from_date;
            $party->from_time=$from_time;
            $party->password=$password;
            $party->phone=$phone;
            $party->summary=$summary;
            $party->cupping=$cupping;
            $party->status=1;

            if($party->save())
            {
                $sale=new Sales;
                $sale->name="杯测活动";
                $sale->body="杯测活动";
                $sale->party_id=$party->id;
                $sale->price=$price;
                $sale->original_price=$price;
                $sale->sale_no = rand(100000,999999);
                $sale->save();
            }
        }

        
        return response()->json($party);
    }
    /*
     * party
     */
    public function Impl_saleUpdate(Request $request){
        $sale_id=$request->input('sale_id');
        $supply_id=$request->input('supply_id');
        $price=$request->input('price');
        $specification_id=$request->input('specification_id');
        $specification_name=$request->input('specification_name');
        $goods_id=$request->input('goods_id');
        // $banner=$request->input('banner');

        

        if($sale_id>0)
        {
            $sale=Sales::find($sale_id);
            $sale->price=$price;
            $sale->specification_id=$specification_id;
            $sale->specification_name=$specification_name;
            $sale->goods_id=$goods_id;
            $sale->save();
        }
        else
        {
            $sale=new Sales;

            if($goods_id)
                $info=Goods::find($goods_id);
            if($supply_id)
                $info=Supplys::find($goods_id);

            $sale->name=$info->name;
            if($specification_id)
            {
                $specification=Tags::find($specification_id);
                $sale->body=$specification->name;
            }

            
            // $sale->party_id=$party->id;
            $sale->supply_id=$supply_id;
            $sale->price=$price;
            $sale->specification_id=$specification_id;
            $sale->specification_name=$specification_name;
            $sale->goods_id=$goods_id;
            $sale->original_price=$price;
            $sale->sale_no = rand(100000,999999);
            $sale->save();
        }

        
        return response()->json($sale);
    }
    public function Impl_saleDel(Request $request){
        Sales::where('id', '=', $request->input('sale_id'))->delete();       
    }

    public function Impl_saleDetail(Request $request){
        $sale_id=$request->input('sale_id');
        $sale=Sales::find($sale_id);

        return response()->json($sale);       
    }
    public function Impl_saleOrderList(Request $request){
        $partner_id=$request->input('partner_id');
        // $user = $this->getUserByAppUserSession($request->input('loginSession'));

        $saleOrders=Sale_order::all();
        $goods=Goods::where("partner_id",$partner_id)->get();

        $goodsArr=array();
        foreach ($goods as $good) {
            array_push($goodsArr, $good->id);
        }
        $sales = DB::table('sale')
                     ->whereIn('goods_id', $goodsArr)
                     ->get();

        $salesArr=array();
        foreach ($sales as $sale) {
            array_push($salesArr, $sale->id);
        }

        $saleOrders = DB::table('sale_order')
                     ->whereIn('sale_id', $salesArr)
                     ->orderBy('id', 'desc')
                     ->get();

        foreach ($saleOrders as $saleOrder) {
            // $sale = $saleOrder->getSale();
            $saleOrder->sale=Sales::find($saleOrder->sale_id);
            $saleOrder->address=DeliveryAddress::find($saleOrder->address_id);
        }


        return response()->json($saleOrders);       
    }
    public function Impl_saleOrderDetail(Request $request){
        $saleOrder_id=$request->input('saleOrder_id');

        $saleOrder=Sale_order::find($saleOrder_id);
        $saleOrder->sale=Sales::find($saleOrder->sale_id);
        $saleOrder->address=DeliveryAddress::find($saleOrder->address_id);

        return response()->json($saleOrder);       
    }
    public function Impl_updateSaleOrderDeliver(Request $request){
        $saleOrder_id=$request->input('saleOrder_id');
        $deliver_number=$request->input('deliver_number');

        $saleOrder=Sale_order::find($saleOrder_id);
        $saleOrder->deliver_number=$deliver_number;

        $saleOrder->save();
        return response()->json($saleOrder);       
    }

    public function Impl_taskUpdate(Request $request){
        $task_id=$request->input('task_id');
        $address_id=$request->input('address_id');
        $sale_id=$request->input('sale_id');
        $goods_id=$request->input('goods_id');

        if($task_id>0)
        {
            $task=tasks::find($task_id);
            $task->price=$price;
            $task->specification_id=$specification_id;
            $task->specification_name=$specification_name;
            $task->goods_id=$goods_id;
            $task->save();
        }
        else
        {
            $task=new tasks;
            $task->sale_id=$sale_id;
            $task->goods_id=$goods_id;
            $task->address_id=$address_id;
            
            $task->save();
        }   
        return response()->json($task);
    }
    public function Impl_taskList(Request $request){
        $tasks = Tasks::orderBy('created_at', 'desc')
               ->take(100)
               ->get();
        foreach ($tasks as $task) {
            $task->address;
            $task->goods;
            $task->sale;
        }
        return response()->json($tasks);

    }
    public function Impl_taskDetail(Request $request){
        $task_id=$request->input('task_id');

        $task=Tasks::find($task_id);
        $task->address;
        $task->goods;
        $task->sale;

        return response()->json($task);

    }
    
    



    public function Impl_partyUserCreate(Request $request){
        $party_id=$request->input('party_id');
        $user = $this->getUserByAppUserSession($request->input('loginSession'));
        $formId = $request->prepay_id;

        $party=Party::find($party_id);
        $cafe = $party->cafe;
        $partyUser=new Party_user;
        $partyUser->party_id=$party_id;
        $partyUser->user_id=$user->id;


        $toPartyUserMsg = collect();
        $keyword1=['value' => $party->name, 'color' => '#000000'];
        $keyword2=['value' => $cafe->name."，地址：".$cafe->address, 'color' => '#000000'];
        $keyword3=['value' => $party->from_date . ' ' . $party->from_time, 'color' => '#000000'];
        $keyword4=['value' => '点击查看更多活动以及导航等信息', 'color' => '#000000'];
        $toPartyUserMsg->put('keyword1', $keyword1);
        $toPartyUserMsg->put('keyword2', $keyword2);
        $toPartyUserMsg->put('keyword3', $keyword3);
        $toPartyUserMsg->put('keyword4', $keyword4);

        
        if($partyUser->save())
            $this->sendTemplateMsg($user->wx_app_openid, '2s4tb11JnmiCgj_WNIgt-HJ01A4kX_VGvKK1h9F53Lo', '/pages/front/party/detail/detail?id='.$party->id, $formId, $toPartyUserMsg);

        return response()->json($partyUser);
    }
    public function Impl_cuppingDataNew(Request $request){
        $party_id=$request->input('party_id');
        $supply_id=$request->input('supply_id');
        $tag_id=$request->input('tag_id');
        $score=$request->input('score');
        $words=$request->input('words');
        $user = $this->getUserByAppUserSession($request->input('loginSession'));
        
        


        $cd = Cupping_data::where('party_id', '=', $party_id)->where('supply_id', '=', $supply_id)->where('tag_id', '=', $tag_id)->where('user_id', '=', $user->id)->first();

        if(empty($cd))
        {
            $cuppingData=new Cupping_data;
            $cuppingData->party_id=$party_id;
            $cuppingData->supply_id=$supply_id;
            $cuppingData->tag_id=$tag_id;
            $cuppingData->user_id=$user->id;
            $cuppingData->score=$score;
            $cuppingData->words=$words;
            $cuppingData->save();
            return response()->json($cuppingData);
            
        }
        else
        {
            $cuppingData=Cupping_data::find($cd->id);
            $cuppingData->party_id=$party_id;
            $cuppingData->supply_id=$supply_id;
            $cuppingData->tag_id=$tag_id;
            $cuppingData->user_id=$user->id;
            $cuppingData->score=$score;
            $cuppingData->words=$words;
            $cuppingData->save();
            return response()->json($cuppingData);
        } 
        return response()->json($cuppingData);
    }
    public function Impl_partyBeanCreate(Request $request){
        
        $party_id=$request->input('party_id');
        $supply_id=$request->input('supply_id');
        $number=$request->input('number');
        

        $ps = Party_supply::where('party_id', '=', $party_id)->where('supply_id', '=', $supply_id)->first();

        if(empty($ps))
        {
            $partySupply=new Party_supply;
            $partySupply->party_id=$party_id;
            $partySupply->supply_id=$supply_id;
            $partySupply->number=$number;
            $partySupply->save();

            return response()->json($partySupply);
            
        }
        else
        {
            $partySupply=Party_supply::find($ps->id);
            $partySupply->party_id=$party_id;
            $partySupply->supply_id=$supply_id;
            $partySupply->number=$number;
            $partySupply->save();

            return response()->json($partySupply);
        }    
        
    }
    public function Impl_partyBeanDel(Request $request){
        
        $party_id=$request->input('party_id');
        $supply_id=$request->input('supply_id');
        $number=$request->input('number');
        
        Party_supply::where('party_id', '=', $party_id)->where('number', '=', $number)->delete();       
    }

    /*
     * appSupply接口
     */
    public function Impl_simpleSupplyCreate(Request $request){
        $name=$request->input('name');
        $body=$request->input('body');
        $cafe=$request->input('cafe');
        $category=$request->input('category');
        
        $supply=new Supplys;
        $supply->cafe=$cafe;
        $supply->name=$name;
        $supply->body=$body;
        $supply->category=$category;
        $supply->public=0;

        if($supply->save())
        {
            $cafeSupply = new Cafes_supplys;
            $cafeSupply->cafe_id = $cafe;
            $cafeSupply->supply_id = $supply->id;
            $cafeSupply->save();
        }
        return response()->json($supply);
    }
    public function Impl_supplyCreate(Request $request){
        $flavours = explode(',', $request->input('flavourStr'));

        $barista_id=$request->input('barista_id');
        $name=$request->input('name');
        $name2=$request->input('name2');
        $body=$request->input('body');
        $cafe=$request->input('cafe');
        //杯测关联数据
        $party_id=$request->input('party_id');
        $sampleNumber=$request->input('sampleNumber');

        
        $continent=$this->getDictValue('continent',$request->input('continent')+1); //得到处理方式tagid
        $country=$this->getTagID($continent,$request->input('country')+1); //得到处理方式tagid
        $method=$this->getTagID(15,$request->input('method')+1); //得到处理方式tagid
        $roast=$this->getTagID(18,$request->input('roast')+1); //得到处理方式tagid
        $species=$this->getTagID(13,$request->input('species')+1); //得到处理方式tagid
        $farm=$request->input('farm');
        $height1=$request->input('height1');
        $height2=$request->input('height2');
        $taste=$request->input('taste');
        $fragrance=$request->input('fragrance');
        $acidity=$request->input('acidity');
        $sweet=$request->input('sweet');
        $tasteBody=$request->input('tasteBody');
        $tasteBack=$request->input('tasteBack');
        $category=$request->input('category');
        
        $supply=new Supplys;
        $supply->cafe=$cafe;
        $supply->barista_id=$barista_id;
        $supply->continent=$continent;
        $supply->country=$country;
        $supply->name=$name;
        $supply->name2=$name2;
        $supply->body=$body;
        $supply->farm=$farm;
        $supply->height1=$height1;
        $supply->height2=$height2;
        $supply->method=$method;
        $supply->roast=$roast;
        $supply->species=$species;
        $supply->fragrance=$fragrance;
        $supply->taste=$taste;
        $supply->acidity=$acidity;
        $supply->sweet=$sweet;
        $supply->tasteBody=$tasteBody;
        $supply->tasteBack=$tasteBack;
        $supply->category=$category;
        $supply->public=0;

        if($supply->save())
        {
            //更新咖啡馆的豆子库
            $cafeSupply = new Cafes_supplys;
            $cafeSupply->cafe_id = $cafe;
            $cafeSupply->supply_id = $supply->id;
            $cafeSupply->save();

            //更新杯测相关信息
            if($party_id)
            {
                $partySupply=new Party_supply;
                $partySupply->party_id=$party_id;
                $partySupply->supply_id=$supply->id;
                $partySupply->number=$sampleNumber;

                $partySupply->save();
            }
            else
            {
                Supply_tags::where('supply_id',$supply->id)
                    ->delete();
                foreach ($flavours as $flavour) {
                    if(!empty($flavour))
                    {
                        $sf=new Supply_tags();
                        $sf->supply_id=$supply->id;
                        $sf->tag_id = $flavour;
                        $sf->save();
                    } 
                }
            }
            
        }
        return response()->json($supply);
    }
    public function Impl_supplyUpdate(Request $request){
        $flavours = explode(',', $request->input('flavourStr'));

        var_dump($flavours);
        $name=$request->input('name');
        $name2=$request->input('name2');
        $body=$request->input('body');
        $farm=$request->input('farm');
        $height1=$request->input('height1');
        $height2=$request->input('height2');
        $taste=$request->input('taste');
        $fragrance=$request->input('fragrance');
        $acidity=$request->input('acidity');
        $sweet=$request->input('sweet');
        $tasteBody=$request->input('tasteBody');
        $tasteBack=$request->input('tasteBack');
        $continent=$this->getDictValue('continent',$request->input('continent')+1); //得到处理方式tagid
        $country=$this->getTagID($continent,$request->input('country')+1); //
        $method=$this->getTagID(15,$request->input('method')+1); //得到处理方式tagid
        $roast=$this->getTagID(18,$request->input('roast')+1); //得到处理方式tagid
        $species=$this->getTagID(13,$request->input('species')+1); //得到处理方式tagid
        $supply_id=$request->input('supply_id');
        
        $supply=Supplys::find($supply_id);
        $supply->name=$name;
        $supply->name2=$name2;
        $supply->continent=$continent;
        $supply->country=$country;
        $supply->body=$body;
        $supply->farm=$farm;
        $supply->height1=$height1;
        $supply->height2=$height2;
        $supply->method=$method;
        $supply->roast=$roast;
        $supply->species=$species;
        $supply->fragrance=$fragrance;
        $supply->taste=$taste;
        $supply->acidity=$acidity;
        $supply->sweet=$sweet;
        $supply->tasteBody=$tasteBody;
        $supply->tasteBack=$tasteBack;
        $supply->save();


        Supply_tags::where('supply_id',$supply_id)
            ->delete();
        foreach ($flavours as $flavour) {
            if(!empty($flavour))
            {
                $sf=new Supply_tags();
                $sf->supply_id=$supply->id;
                $sf->tag_id = $flavour;

                $sf->save();
            } 
        }

        return response()->json($supply);
    }
    public function Impl_partySupplyNumber(Request $request){
        $number=$request->input('number');
        $party_id=$request->input('party_id');
        $supply_id=$request->input('supply_id');
        
        $partySupply=Party_supply::where('party_id',$party_id)->where('supply_id',$supply_id)->first();
        $partySupply->number=$number;
        $partySupply->save();
    }

    /*
     * app上传照片接口
     */
    public function Impl_photoCreate(Request $request){
        $cafe_id=$request->input('cafe_id');
        $goods_id=$request->input('goods_id');
        $supply_id=$request->input('supply_id');
        $img=$request->file('img');
        $body=$request->input('body');
        $url = upload_one($img);
        $photo=new Photo;
        $photo->url=$url;
        $photo->body=$body;
        $photo->cafe_id=$cafe_id;
        $photo->goods_id=$goods_id;
        $photo->supply_id=$supply_id;
        $photo->save();
        return response()->json($photo);
    }

    public function Impl_photoUpdate(Request $request){
        $id = $request->input('id');
        $url = $request->input('url');
        $goods_id = $request->input('goods_id');

        // $url = substr($url, 0, 26);
        if($url)
            $url = substr($url, 0, 26) . "pictj" . substr($url, 31);

        $sort = $request->input('sort');
        $body = $request->input('body');
        if($body=='null')
            $body='';
        $cafe = $request->input('cafe');
        $message = $request->input('message')?$request->input('message'):0;

        if($id)
        {
            $photo=Photo::find($id);
            if($url)
                $photo->url=$url;
            if($goods_id)
                $photo->goods_id=$goods_id;
            if($message)
                $photo->message_id=$message;
            if($sort)
                $photo->sort=$sort;

            if(isset($body))
                $photo->body=$body;

            $photo->save();
        }
        else
        {
            $photo=new Photo;
            $photo->cafe_id=$cafe;
            $photo->message_id=$message;
            $photo->goods_id=$goods_id;
            $photo->url=$url;
            if(str_contains($url, "http://onecafe")){
                $url=$url."?imageInfo";
                $rs=dealHttp($url);
                $width=$rs->width;
                $height=$rs->height;
                $photo->width=$width;
                $photo->height=$height;
            }
            $photo->sort=$sort;
            $photo->save();
        }

    }
    public function Impl_photoDel(Request $request){
        $id = $request->input('id');

        if($id)
        {
            $photo=Photo::find($id);
            $photo->delete();
        }
    }

    public function Impl_photoSort(Request $request){
        $op = $request->input('op');
        $pre = $request->input('id')-1;
        $now = $request->input('id');
        $after = $request->input('id')+1;
        $sort=1;

        if($request->input('cafe'))
        {
            $cafe=Cafe::find($request->input('cafe'));
            $photos=$cafe->photos()->get();
        }
        if($request->input('supply'))
        {
            $supply=Supplys::find($request->input('supply'));
            $photos=$supply->photos()->get();
            var_dump($photos);
        }
        if($photos->count()>9){
            $photos=$photos->sortBy('sort')->take(9);
        }else{
            $photos=$photos->sortBy('sort');
        }

        switch ($op) {
            case 'up':
                foreach ($photos as $photo) {
                    if($sort==$pre)
                    {
                        $photo->sort = $pre+1;
                        $photo->save();
                    }
                    if($sort==$now)
                    {
                        $photo->sort = $now-1;
                        $photo->save();
                    }
                    $sort++;
                }
                break;
            case 'down':
                foreach ($photos as $photo) {
                    if($sort==$now)
                    {
                        $photo->sort = $now+1;
                        $photo->save();
                    }
                    if($sort==$after)
                    {
                        $photo->sort = $after-1;
                        $photo->save();
                    }
                    $sort++;
                }
                break;
            case 'del':
                foreach ($photos as $photo) {
                    if($sort==$now)
                    {
                        $photo->delete();
                    }
                    $sort++;
                }
                break;
            default:
                # code...
                break;
        }
    }

    //message
    public function Impl_messageCreate(Request $request){
        $cafe_id=$request->input('cafe_id');
        $summary=$request->input('summary');
        $user = $this->getUserByAppUserSession($request->input('loginSession'));
        $message=new Message;
        $message->summary=$summary;
        $message->cafe_id=$cafe_id;
        $message->user_id=$user->id;
        $message->save();
        return response()->json($message);
    }
    //Impl_deliveryAddressCreate
    public function Impl_deliveryAddressCreate(Request $request){
        
        $user = $this->getUserByAppUserSession($request->input('loginSession'));
        $deliveryAddress=new DeliveryAddress;
        $deliveryAddress->user_id=$user->id;

        $deliveryAddress->userName=$request->input('userName');
        $deliveryAddress->postalCode=$request->input('postalCode');
        $deliveryAddress->provinceName=$request->input('provinceName');
        $deliveryAddress->cityName=$request->input('cityName');
        $deliveryAddress->countyName=$request->input('countyName');
        $deliveryAddress->detailInfo=$request->input('detailInfo');
        $deliveryAddress->nationalCode=$request->input('nationalCode');
        $deliveryAddress->telNumber=$request->input('telNumber');
        $deliveryAddress->save();
        return response()->json($deliveryAddress);
    }

    //查询快递
    public  function Impl_selectTrade(Request $request){
        $tradeNo=$request->tradeNo;

        $host = "http://jisukdcx.market.alicloudapi.com";
        $path = "/express/query";
        $method = "GET";
        $appcode = "b38de016e7c24ba8b9e3d478b18cbfa4";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "number=$tradeNo&type=auto";
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($curl, CURLOPT_HEADER, true);
//        curl_setopt($curl, CURLINFO_HEADER_OUT, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        return response()->json(json_decode(curl_exec($curl)));
    }

    private  function  getPickerDataFromTags($dict,$tag_value){
        $tagsArr=array();
        $tags=Dicts::find($dict)->showtags()->get();
        $index=Tags::where('value',$tag_value)->first()->sort;
        $tagsArr['tags']=$tags;
        $tagsArr['index']=$index;
        return $tagsArr;
    }
    private  function  getPickerDataFromDicts($category,$dict){
        $dictsArr=array();
        $dicts=Dicts::where('category', $category)->get();
        $index=Dicts::find($dict)->sort;
        $dictsArr['dicts']=$dicts;
        $dictsArr['index']=$index;
        return $dictsArr;
    }

    private  function  getTagID($dict,$tag_index){
        $value=Tags::where('category',$dict)->where('sort',$tag_index)->first()->id;
        return $value;
    }
    private  function  getDictValue($category,$sort){
        $dicts = DB::table('dicts')
                     ->where('category', $category)
                     ->where('sort', $sort)
                     ->get();
        $dict = $dicts[0];
        return $dict->id;
    }

    public function Impl_getPickerDataFromDicts(Request $request)
    {
        $data=Dicts::find($request->input('dict'))->showtags()->get();
        $id=0;
        $pickerData=$this->getPickerDataFromArr($data, $id);
        return response()->json($pickerData);
    }
    public function Impl_getPickerDataFromTags(Request $request)
    {
        $dict=$request->input('dict');
        $tag_id=$request->input('tag_id');
        $partner_id=$request->input('partner_id');

        if(empty($tag_id))
            $tag_id=0;




        $data=Tags::where('category',$dict)->where('partner_id',$partner_id)->get();
        return response()->json($this->getPickerDataFromArr($data,$tag_id));
    }
    private function getPickerDataFromArr($arr,$id)
    {
        $pickerData = $arr->sortBy("sort");   //排序
        $index=0;
        $pickerIndex=0;
        foreach ($pickerData as $row) {
            $row->sort=$index;
            if($row->id==$id)
                $pickerIndex=$row->sort;
            $index++;
        }

        $pickerArr=array();
        foreach ($pickerData as $row) {
            array_push($pickerArr, $row);
        }


        $returnArr=array();             //包装数据返回
        $returnArr['pickerData']=$pickerArr;
        $returnArr['index']=$pickerIndex;
        return $returnArr;
    }
    private function getIdFromPickerData($arr,$index)
    {

    }

    private function getUserByAppUserSession($loginSession){
        $wx_app_openid=Redis::get($loginSession);
        if($wx_app_openid)
        {
            $user = DB::table('users')->select("id","wx_app_openid","nickname","headimgurl")->where('wx_app_openid', $wx_app_openid)->first();
            return $user;
        }
        else
            return false;
        
    }
    private function sendTemplateMsg($toUser, $templateId, $page, $formId, $data){
        $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb980d6dc4b2c0314&secret=4e1e32a82b0e24c7570e1555f1d71fe6";
        $res=dealHttp($access_token_url);
        $access_token=$res->access_token;
        $url="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token;
        $ch = curl_init($url);
        $data = array("touser" => $toUser,"template_id"=>$templateId,"page"=>$page,"form_id"=>$formId,"data"=>$data);
        $data_string = json_encode($data);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );
        $json_data = curl_exec($ch);
        curl_close($json_data);
        $array = json_decode($json_data,true);
    }
    private  function sendTradeSms($partnerID){
        $users=UserPartner::where('partner_id',$partnerID)->get();
        foreach ($users as $user){
            $phone=$user->user->phone;
            $content="您有新的订单需要发货";
            sendSms($phone,$content);
        }

    }


}
